package com.hdrx.fundhelper.service.user;

import cn.hutool.core.util.ObjectUtil;
import com.hdrx.fundhelper.dao.pojo.User;
import com.hdrx.fundhelper.dao.pojo.Userinfo;
import com.hdrx.fundhelper.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: houdx
 * @description:
 * @date: 2023/6/19 14:19
 */
@Service
@Slf4j
public class UserService {
    @Resource
    UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    TransactionTemplate transactionTemplate;


    public Userinfo queryUserById(Integer id) {
        log.info("查询方法入参：{}", id);
        Userinfo userinfo = userInfoMapper.selectByPrimaryKey(id);
        return userinfo;
    }


    public void addUser(Userinfo userinfo) {

        Userinfo userinfo1 = userInfoMapper.selectByPrimaryKey(userinfo.getUserId());
        if (ObjectUtil.isNotEmpty(userinfo1)){

            transactionTemplate.execute(status -> {
                try {
                    userInfoMapper.insert(userinfo);
                } catch (Exception e) {
                    log.error("新增异常{}", e.getMessage());
                    status.setRollbackOnly();
                    throw new RuntimeException(e.getMessage());
                }
                return Boolean.TRUE;
            });
        }

    }

    public Userinfo queryUser(Integer id) {
        ValueOperations value = redisTemplate.opsForValue();
        //查缓存
        Object o = value.get(String.valueOf(id));
        //缓存命中
        if (o != null) {
            log.info("从redis缓存获取数据{}", o);
            return (Userinfo) o;
        }
        Example example = new Example(Userinfo.class);
        Example.Criteria criteria = example.and();
        criteria.andEqualTo("userId", id);
        criteria.andEqualTo("delFlag", "1");
        Userinfo userinfo = userInfoMapper.selectByExample(example).get(0);
        if (userinfo != null) {
            //放入缓存
            value.set(String.valueOf(id), userinfo);
            log.info("数据存入缓存{}", userinfo);
        }

        return userinfo;
    }


    public int deleteById(Integer id) {
        Userinfo userinfo = new Userinfo();
        userinfo.setDelFlag("0");
        userinfo.setUserId(id);
        //先删数据库，再删缓存
        int row = userInfoMapper.updateByPrimaryKeySelective(userinfo);
        Boolean delete = redisTemplate.delete(String.valueOf(id));

        if (row > 0 && delete) {
            log.info("redis数据删除成功！");
        }
        return row;
    }

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        userList.add(new User("a", "xiaoming","12","1"));
        userList.add(new User("b", "xiaoming","13","2"));
        userList.add(new User("d", "xiaoming","15","1"));
        userList.add(new User("a", "xiaoming","14","1"));

        System.out.println("利用Collectors.toMap去重:");
        //利用Collectors.toMap去重
        userList.stream()
                //或者这样写 Collectors.toMap(m -> m.getId(),
                .collect(Collectors.toMap(User::getId,
                        Function.identity(), (oldValue, newValue) -> oldValue))
                .values()
                .forEach(System.out::println);


    }
}
